package org.smart4j.helper;


import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.util.CollectionUtil;
import org.smart4j.util.PropsUtil;

import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by liquan on 2017/6/12.
 */
public final class DatabaseHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseHelper.class);

    private static QueryRunner QUERY_RUNNER = null;
    private static ThreadLocal<Connection> CONNECTION_THREAD_LOCAL = null;
    private static BasicDataSource DATA_SOURCE = null;

    static {

        CONNECTION_THREAD_LOCAL = new ThreadLocal<>();
        QUERY_RUNNER = new QueryRunner();
        DATA_SOURCE = new BasicDataSource();

        Properties props = PropsUtil.loadProps("config.properties");
        String driver = PropsUtil.getString(props, "jdbc.driver");
        String url = PropsUtil.getString(props, "jdbc.url");
        String userName = PropsUtil.getString(props, "jdbc.username");
        String password = PropsUtil.getString(props, "jdbc.password");

        DATA_SOURCE.setDriverClassName(driver);
        DATA_SOURCE.setUrl(url);
        DATA_SOURCE.setUsername(userName);
        DATA_SOURCE.setPassword(password);
    }

    public static Connection getConn() {
        Connection conn = CONNECTION_THREAD_LOCAL.get();
        try {
            conn = DATA_SOURCE.getConnection();
        } catch (SQLException e) {
            LOGGER.error("get connection failure", e);
        } finally {
            CONNECTION_THREAD_LOCAL.set(conn);
        }
        return conn;
    }


    public static <T> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params) {
        List<T> entityList = null;
        try {
            Connection conn = getConn();
            entityList = QUERY_RUNNER.query(conn, sql, new BeanListHandler<T>(entityClass), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return entityList;
    }


    public static <T> T queryEntity(Class<T> entityClass, String sql, Object... params) {
        T entity = null;
        try {
            Connection conn = getConn();
            entity = QUERY_RUNNER.query(conn, sql, new BeanHandler<T>(entityClass), params);
        } catch (SQLException e) {
            LOGGER.error("execute query list failure ", e);
            throw new RuntimeException(e);
        }
        return entity;
    }

    /**
     * 多表联合查询，查询结果map
     *
     * @param sql
     * @param params
     * @return
     */
    public static List<Map<String, Object>> executeQeury(String sql, Object... params) {
        List<Map<String, Object>> result = null;
        try {
            Connection conn = getConn();
            result = QUERY_RUNNER.query(conn, sql, new MapListHandler(), params);
        } catch (SQLException e) {
            LOGGER.error("execute query failure ", e);
            throw new RuntimeException(e);
        }
        return result;
    }

    public static int executeUpdate(String sql, Object... params) {
        int rows = 0;
        try {
            Connection conn = getConn();
            rows = QUERY_RUNNER.update(conn, sql, params);
        } catch (SQLException e) {
            LOGGER.error("execute update failure ", e);
            throw new RuntimeException(e);
        }
        return rows;
    }

    private static <T> String getTableName(Class<T> entityClass) {
        return entityClass.getSimpleName();
    }

    public static <T> boolean insertEntity(Class<T> entityClass, Map<String, Object> fileMap) {
        if (CollectionUtil.isEmpty(fileMap)) {
            LOGGER.error("can not insert entity , fileMap is empty");
            return false;
        }
        String sql = "INSERT INTO " + getTableName(entityClass);
        StringBuilder columns = new StringBuilder("(");
        StringBuilder values = new StringBuilder("(");
        for (String filedName : fileMap.keySet()) {
            columns.append(filedName).append(", ");
            values.append("? ,");
        }
        columns.replace(columns.lastIndexOf(","), columns.length(), " )");
        values.replace(values.lastIndexOf(","), values.length(), " )");

        sql += columns + " VALUES " + values;

        Object[] params = fileMap.values().toArray();
        return executeUpdate(sql, params) == 1;
    }

    public static <T> boolean updateEntity(Class<T> entityClass, long id, Map<String, Object> fileMap) {
        if (CollectionUtil.isEmpty(fileMap)) {
            LOGGER.error("can not update entity , fileMap is empty");
            return false;
        }
        String sql = "UPDATE " + getTableName(entityClass) + " SET ";
        StringBuilder columns = new StringBuilder();
        for (String filedName : fileMap.keySet()) {
            columns.append(filedName).append("=").append("=? ,");
        }
        columns.replace(columns.lastIndexOf(","), columns.length(), " WHERE id=?");
        List<Object> paramList = new ArrayList();
        paramList.addAll(fileMap.values());
        paramList.add(id);
        Object[] params = paramList.toArray();
        return executeUpdate(sql, params) == 1;
    }

    public static <T> boolean deleteEntity(Class<T> entityClass, long id) {
        String sql = "DELETE FROM " + getTableName(entityClass) + " WHERE id=?";
        return executeUpdate(sql, id) == 1;
    }

    public static void executeSqlFile(String filePath) {
        try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath)) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String sql;
            while ((sql = reader.readLine()) != null) {
                executeUpdate(sql);
            }
        } catch (IOException e) {
            LOGGER.error("find sql file failure ", e);
            throw new RuntimeException(e);
        }
    }
}
